package com.eduagent.xwqeduagent.tools;

import com.eduagent.xwqeduagent.app.agent.WebScrapingService;
import com.eduagent.xwqeduagent.model.vo.WebScrapingResultVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

/**
 * 基于自实现的网页抓取工具
 * 通过Spring AI框架提供网页抓取功能，支持结构化网页内容解析
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class WebScrapingServiceTool {

    private final WebScrapingService webScrapingService;

    @Tool(description = "Extract content from web pages including title, text, links, and images. " +
            "This tool can scrape web pages and return structured content including page title, " +
            "main text content, all links found on the page, and image URLs.")
    public String scrapeWebPage(
            @ToolParam(description = "Target URL to scrape - the web page URL you want to extract content from")
            String targetUrl) {
        
        // 生成一个会话ID用于本次抓取
        String sessionId = "tool_scrape_" + System.currentTimeMillis();
        String userId = "spring_ai_tool";
        
        log.info("Spring AI工具开始网页抓取，URL：{}", targetUrl);
        
        try {
            // 调用网页抓取服务
            WebScrapingResultVO result = webScrapingService.performWebScraping(targetUrl, userId, sessionId);
            
            if ("success".equals(result.getStatus())) {
                // 格式化抓取结果为易读的字符串
                return formatScrapingResult(result);
            } else {
                return "网页抓取失败：" + result.getMessage();
            }
        } catch (Exception e) {
            log.error("Spring AI工具网页抓取异常", e);
            return "网页抓取出现异常：" + e.getMessage();
        }
    }

    /**
     * 批量网页抓取工具
     */
    @Tool(description = "Extract content from multiple web pages in batch. " +
            "This tool can scrape multiple URLs and return structured content for each page.")
    public String scrapeMultipleWebPages(
            @ToolParam(description = "List of URLs to scrape, separated by commas or semicolons") 
            String urls) {
        
        // 生成一个会话ID用于本次批量抓取
        String sessionId = "tool_batch_scrape_" + System.currentTimeMillis();
        String userId = "spring_ai_tool";
        
        log.info("Spring AI工具开始批量网页抓取，URLs：{}", urls);
        
        try {
            // 解析URL列表
            String[] urlArray = urls.split("[,;\\n]");
            java.util.List<String> urlList = new java.util.ArrayList<>();
            for (String url : urlArray) {
                String trimmedUrl = url.trim();
                if (!trimmedUrl.isEmpty()) {
                    urlList.add(trimmedUrl);
                }
            }
            
            if (urlList.isEmpty()) {
                return "未提供有效的URL列表";
            }
            
            // 限制批量抓取数量
            if (urlList.size() > 5) {
                urlList = urlList.subList(0, 5);
                log.info("限制批量抓取数量为5个，实际处理：{}", urlList.size());
            }
            
            // 调用批量网页抓取服务
            java.util.List<WebScrapingResultVO> results = webScrapingService.performBatchWebScraping(urlList, userId, sessionId);
            
            // 格式化批量抓取结果
            return formatBatchScrapingResult(results);
            
        } catch (Exception e) {
            log.error("Spring AI工具批量网页抓取异常", e);
            return "批量网页抓取出现异常：" + e.getMessage();
        }
    }

    /**
     * 网页摘要抓取工具
     */
    @Tool(description = "Extract summary information from web page including only title and brief content. " +
            "This tool provides a quick overview of web page content without detailed extraction.")
    public String scrapeWebPageSummary(
            @ToolParam(description = "Target URL to get summary from") 
            String targetUrl) {
        
        String sessionId = "tool_summary_" + System.currentTimeMillis();
        String userId = "spring_ai_tool";
        
        log.info("Spring AI工具开始网页摘要抓取，URL：{}", targetUrl);
        
        try {
            WebScrapingResultVO result = webScrapingService.performWebScraping(targetUrl, userId, sessionId);
            
            if ("success".equals(result.getStatus())) {
                return formatSummaryResult(result);
            } else {
                return "网页摘要抓取失败：" + result.getMessage();
            }
        } catch (Exception e) {
            log.error("Spring AI工具网页摘要抓取异常", e);
            return "网页摘要抓取出现异常：" + e.getMessage();
        }
    }

    /**
     * 格式化抓取结果为AI易理解的文本格式
     * @param result 抓取结果对象
     * @return 格式化后的文本
     */
    private String formatScrapingResult(WebScrapingResultVO result) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("网页抓取完成！目标URL：").append(result.getTargetUrl()).append("\n\n");
        
        // 基本信息
        sb.append("【页面标题】").append(result.getTitle()).append("\n\n");
        
        // 文本内容
        if (result.getTextContent() != null && !result.getTextContent().isEmpty()) {
            String content = result.getTextContent();
            // 如果内容太长，截取前2000字符
            if (content.length() > 2000) {
                content = content.substring(0, 2000) + "...[内容过长，已截取]";
            }
            sb.append("【页面内容】\n").append(content).append("\n\n");
        }
        
        // 链接信息
        if (result.getLinks() != null && !result.getLinks().isEmpty()) {
            sb.append("【页面链接】找到 ").append(result.getLinks().size()).append(" 个链接：\n");
            int linkCount = 0;
            for (String link : result.getLinks()) {
                sb.append("• ").append(link).append("\n");
                linkCount++;
                if (linkCount >= 10) { // 限制显示前10个链接
                    sb.append("... 还有 ").append(result.getLinks().size() - 10).append(" 个链接\n");
                    break;
                }
            }
            sb.append("\n");
        }
        
        // 图片信息
        if (result.getImages() != null && !result.getImages().isEmpty()) {
            sb.append("【页面图片】找到 ").append(result.getImages().size()).append(" 个图片：\n");
            int imgCount = 0;
            for (String img : result.getImages()) {
                sb.append("• ").append(img).append("\n");
                imgCount++;
                if (imgCount >= 5) { // 限制显示前5个图片
                    sb.append("... 还有 ").append(result.getImages().size() - 5).append(" 个图片\n");
                    break;
                }
            }
            sb.append("\n");
        }
        
        // 统计信息
        sb.append("【抓取统计】\n");
        sb.append("内容长度：").append(result.getContentLength()).append(" 字符\n");
        sb.append("抓取时间：").append(result.getScrapeTime()).append("\n");
        
        return sb.toString();
    }

    /**
     * 格式化批量抓取结果
     */
    private String formatBatchScrapingResult(java.util.List<WebScrapingResultVO> results) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("批量网页抓取完成！共处理 ").append(results.size()).append(" 个网页：\n\n");
        
        int successCount = 0;
        int failCount = 0;
        
        for (int i = 0; i < results.size(); i++) {
            WebScrapingResultVO result = results.get(i);
            sb.append("【").append(i + 1).append("】").append(result.getTargetUrl()).append("\n");
            
            if ("success".equals(result.getStatus())) {
                successCount++;
                sb.append("✓ 抓取成功 - ").append(result.getTitle()).append("\n");
                if (result.getTextContent() != null) {
                    String preview = result.getTextContent().length() > 200 ? 
                            result.getTextContent().substring(0, 200) + "..." : 
                            result.getTextContent();
                    sb.append("内容预览：").append(preview).append("\n");
                }
            } else {
                failCount++;
                sb.append("✗ 抓取失败 - ").append(result.getMessage()).append("\n");
            }
            sb.append("\n");
        }
        
        sb.append("【批量抓取统计】\n");
        sb.append("成功：").append(successCount).append(" 个，失败：").append(failCount).append(" 个\n");
        
        return sb.toString();
    }

    /**
     * 格式化摘要结果
     */
    private String formatSummaryResult(WebScrapingResultVO result) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("网页摘要抓取完成！\n\n");
        sb.append("【URL】").append(result.getTargetUrl()).append("\n");
        sb.append("【标题】").append(result.getTitle()).append("\n");
        
        if (result.getTextContent() != null && !result.getTextContent().isEmpty()) {
            String summary = result.getTextContent().length() > 500 ? 
                    result.getTextContent().substring(0, 500) + "..." : 
                    result.getTextContent();
            sb.append("【内容摘要】").append(summary).append("\n");
        }
        
        sb.append("【统计】内容长度：").append(result.getContentLength()).append(" 字符");
        if (result.getLinks() != null) {
            sb.append("，链接数：").append(result.getLinks().size());
        }
        if (result.getImages() != null) {
            sb.append("，图片数：").append(result.getImages().size());
        }
        
        return sb.toString();
    }
}